package com.wangxiaonan.wxwork.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.wangxiaonan.wxwork.exeption.ServiceException;
import com.wangxiaonan.wxwork.service.TokenService;
import com.wangxiaonan.wxwork.util.HttpUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class TokenServiceImpl implements TokenService {
    private static final Logger logger = LoggerFactory.getLogger(TokenServiceImpl.class);

    @Override
    public JSONObject getToken(String corpId, String corpSecret) {
        logger.info("[TokenServiceImpl] {} | getToken >>> corpId: {}, corpSecret: {}", new Date(), corpId, corpSecret);
        if (StringUtils.isBlank(corpId) || StringUtils.isBlank(corpSecret)) {
            throw new ServiceException("param_invalid", "参数不能为空");
        }
        String result;
        try {
            String url = String.format(TokenService.DEFAULT_GET_TOKEN_URL, corpId, corpSecret);
            result = HttpUtil.get(url);
        } catch (Exception e) {
            throw new ServiceException("connect_refuse", "接口请求失败");
        }
        JSONObject jsonObject;
        try {
            jsonObject = JSONObject.parseObject(result);
        } catch (Exception e) {
            logger.error("[TokenServiceImpl] getToken >> result: {}", result);
            throw new ServiceException("object_format_error", "请求结果格式化错误");
        }

        return jsonObject;
    }


    @Override
    @Cacheable(value = "tokens", key = "#corpId+'_'+#corpSecret")
    @Retryable(value = {ServiceException.class})
    public String getTokenString(String corpId, String corpSecret) {
        JSONObject jsonObject = getToken(corpId, corpSecret);
        if ("0".equals(jsonObject.getString("errcode"))) {
            return jsonObject.getString("access_token");
        } else {
            throw new ServiceException(jsonObject.getString("errcode"), jsonObject.getString("errmsg"));
        }
    }

    @Recover
    public String recover(ServiceException se, String corpId, String corpSecret) {
        logger.error("[TokenServiceImpl] recover get token fail >>> {} : {}", corpId, corpSecret, se);
        throw new ServiceException(se.getCode(), se.getMsg());
    }
}
